package com.ljsw.util;

import com.ljsw.activity.R;
import com.ljsw.dialog.DeleteDialog;
import com.ljsw.entity.User;
import com.ljsw.server.UpServer;

import poka_global_constant.GlobalConstant;
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.graphics.Bitmap.Config;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Toast;
import android_serialport_api.SerialPort;
import cn.poka.device.FingerDevice;
import cn.poka.util.PokaContext;
import cn.poka.util.RFIDProtocol;

/**
 * @ClassName: FingerUtil
 * @Description: 指纹识别工具类
 * @author dg
 * @date 2016-1-19 下午3:36:17
 */
public class FingerUtil {
	private Context context;
	private FingerHandler fingerHandler = new FingerHandler();
	private FingerThread fingerThread;
	private OnGetFingerListener mFingerListener;
	private static final int FINGER_SUCCESS = 0;
	private static final int FINGER_FAIL = 1;
	public interface OnGetFingerListener {
		void getFingerValue(byte[] value);

		void getFingerBitmap(Bitmap bitmap);

		void getFingerSuccess(User user);

		void getFingerFail();
		
	}
	public FingerUtil(Context context, OnGetFingerListener mFingerListener) {
		this.context = context;
		this.mFingerListener = mFingerListener;
		PokaContext.init(context.getApplicationContext());
	}

	public Thread getThread() {
		return fingerThread;
	}

	public void startFinger() {
		FingerDevice.getInstance().enable();
		fingerHandler.sendMessageDelayed(fingerHandler.obtainMessage(21), 50);
	}

	public void stopFinger() {
		fingerHandler.sendMessageDelayed(fingerHandler.obtainMessage(31), 0);
	}

	public void stopControl() {
		fingerThread.stopControl();
	}

	public void startControl() {
		fingerThread.startControl();
	}

	public void startTconfrim(String corpId, String roleId, byte[] cValue) {
		TconfirmFinger mTconfrimFinger = new TconfirmFinger(corpId, roleId,
				cValue);
		mTconfrimFinger.start();
	}

	public boolean isStart() {
		if (fingerThread.control == true && fingerThread.flag == true) {
			return true;
		}
		return false;
	}

	@SuppressLint("HandlerLeak")
	class FingerHandler extends Handler {

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case 11:
				if (context != null) {
					Toast.makeText(context, "正在验证指纹..", Toast.LENGTH_SHORT)
							.show();
				}

				break;
			case 21:
				doFirst();
				break;
			case 22:
				doSecond();
				break;
			case 31:
				quit();
				break;
			case 51:
				byte[] ival = (byte[]) msg.obj;
				String result = RFIDProtocol.byteToHexString(ival);
				mFingerListener.getFingerValue(ival);
				break;
			case 52:
				Bitmap bmp = (Bitmap) msg.obj;
				mFingerListener.getFingerBitmap(bmp);
				break;
			case 61:

				if (context != null) {
					Toast.makeText(context, "无结果", Toast.LENGTH_SHORT).show();
				}
				break;
			default:
				break;
			}
		}

	}

	private void doFirst() {
		Log.d("tag__", "-------doFirst-------");
		FingerDevice.getInstance().enroll();

		Message msg = fingerHandler.obtainMessage();
		msg.what = 22;
		fingerHandler.sendMessage(msg);
	}

	private void doSecond() {
		Log.d("tag__", "-------doSecond-------");
		try {
			Thread.sleep(50);

			if (fingerThread == null) {
				fingerThread = new FingerThread();
			}
			if(!fingerThread.flag){
				fingerThread.startControl();
				fingerThread.startThread();
				fingerThread.start();
			}
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

	private void quit() {
		Log.d("tag__", "----�˳�--quit-------");
		String close = "QUIT";
		byte[] tt = close.getBytes();
		byte[] tempclose = new byte[76];
		for (int i = 0; i < tt.length; ++i) {
			tempclose[i] = tt[i];
		}
		FingerDevice.getInstance().getFingerSerialPort().serialWrite(tempclose);
		if (fingerThread != null) {
			fingerThread.stopThread();
			fingerThread = null;
		}
		try {
			Thread.sleep(50);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		if (FingerDevice.getInstance() != null) {
			Log.d("tag__", "关闭设备---------");
			// FingerDevice.getInstance().disenable();
			FingerDevice.getInstance().close();
		}

		// this.finish();
	}

	private void getImage() {
		try {
			byte[] fingerDataBytes = FingerDevice.getInstance()
					.getFingerSerialPort().fingerRead(SerialPort.IMG0);
			if (fingerDataBytes != null && fingerDataBytes.length > 0) {
				Log.d("tag__", "fingerData[0] = " + fingerDataBytes[0]);
				switch (fingerDataBytes[0]) {
				case 2:
					Log.d("tag__", "-------IMG0----");
					int len = fingerDataBytes.length - 1;
					int[] colors = new int[len];
					for (int i = 0; i < len; i++) {
						byte a = fingerDataBytes[i + 1];
						colors[i] = (0xff << 24) + (a << 16) + (a << 8) + (a);
					}
					System.out.println("image 8bit to ARGB-8888 finish!");
					Bitmap img = Bitmap.createBitmap(colors, 76, 100,
							Config.ARGB_8888);
					Bitmap resizeBitmap = Bitmap.createScaledBitmap(img, 190,
							250, true);
					Matrix matrix = new Matrix();
					int width = resizeBitmap.getWidth();
					int height = resizeBitmap.getHeight();
					float matrix_values1[] = { 1f, 0f, 0f, 0f, -1f, 0f, 0f, 0f,
							1f };
					float matrix_values2[] = { -1f, 0f, 0f, 0f, 1f, 0f, 0f, 0f,
							1f };
					matrix.setValues(matrix_values1);
					matrix.postScale(1, -1);
					Bitmap b = Bitmap.createBitmap(resizeBitmap, 0, 0, width,
							height, matrix, true);

					Matrix m = new Matrix();
					m.setValues(matrix_values2);
					m.postRotate(180);
					Bitmap b1 = Bitmap.createBitmap(b, 0, 0, width, height, m,
							true);

					if (fingerHandler != null) {
						Message mg1 = Message.obtain();
						mg1.what = 52;
						mg1.obj = b1;
						fingerHandler.sendMessage(mg1);
						Log.i("FingerDevcie",
								"mg.obj=b1---------->bitmap---right");
					}
					b = null;
					resizeBitmap = null;
					img = null;

					break;
				case 0:
					Message msg = Message.obtain();
					msg.what = 61;
					fingerHandler.sendMessage(msg);
					break;
				}

			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void getReadIval() {
		byte[] fingerData = FingerDevice.getInstance().getFingerSerialPort()
				.fingerReadIval();
		if (fingerData != null && fingerData.length > 0) {
			Log.d("tag__", "fingerData[0] = " + fingerData[0]);
			switch (fingerData[0]) {
			case 1:
				Log.d("tag__", "-------IVAL----");
				Message mg = Message.obtain();
				mg.what = 51;
				mg.obj = GlobalConstant.subBytes(fingerData, 1, 256);
				fingerHandler.sendMessage(mg);
				Log.i("FingerDevcie", "mg.obj=b1---------->IVAL---right");
				break;
			}
		}
	}

	class FingerThread extends Thread {
		public boolean flag = false;
		private boolean control = false;

		public void stopThread() {
			flag = false;
		}

		public void startThread() {
			flag = true;
		}

		public void stopControl() {
			control = false;
		}

		public void startControl() {
			control = true;
		}

		@Override
		public void run() {
			super.run();
			while (flag) {
				int pressed = FingerDevice.getInstance().getFingerSerialPort()
						.isFingerPressed();
				if (control) {

					if (pressed == 1) {
						Message msg = Message.obtain();
						msg.what = 11;
						fingerHandler.sendMessage(msg);

					} else {
						continue;
					}

					getImage();

					getReadIval();
				}
			}

		}
	};

	
	
	class TconfirmFinger extends Thread {
		private String corpId;// 机构类别ID
		private String roleId;// 角色ID
		private byte[] cValue;// 指纹值

		public TconfirmFinger(String corpId, String roleId, byte[] cValue) {
			this.corpId = corpId;
			this.roleId = roleId;
			this.cValue = cValue;

		}

		@Override
		public void run() {
			
			try {

				final User user = UpServer.yanzhengfinger(corpId, roleId,
						cValue);
				/* 指纹验证成功 */
				if (user != null) {
					Message msg=new Message();
					msg.what=FINGER_SUCCESS;
					msg.obj=user;
					mHandler.sendMessage(msg);
				} else if (user == null) {
					/* 指纹验证失败 */
					mHandler.sendEmptyMessage(FINGER_FAIL);
				}
			} catch (Exception e) {
				e.printStackTrace();
				/* 指纹验证异常 */
				mHandler.sendEmptyMessage(FINGER_FAIL);
			}
			mHandler.sendEmptyMessage(8);
		}
	};

	Handler mHandler = new Handler() {
		public void dispatchMessage(Message msg) {
			switch (msg.what) {
			case FINGER_SUCCESS:
				mFingerListener.getFingerSuccess((User)msg.obj);
				break;
			case FINGER_FAIL:
				mFingerListener.getFingerFail();
				break;
			default:
				break;
			}
		};
	};
}
